<template>
  <div class="queryform-container">
    <a-form ref="queryFormRef" :model="queryForm" layout="inline" :label-col="{width:'100px'}">
      <a-form-item :label-col="{ span: 6 }"
                   :wrapper-col="{ span: 16 }" autocomplete="off"
                   label="模板名字"
                   name="templateName">
        <a-input v-model:value="queryForm.templateName" allow-clear/>
      </a-form-item>
      <a-form-item :label-col="{ span: 6 }"
                   :wrapper-col="{ span: 16 }" autocomplete="off"
                   label="源文件类型"
                   name="sourceType">
        <a-input v-model:value="queryForm.sourceType" allow-clear/>
      </a-form-item>
      <a-form-item :label-col="{ span: 8 }"
                   :wrapper-col="{ span: 16 }" autocomplete="off"
                   label="项目"
                   name="projectCode">
        <a-select v-model:value="queryForm.projectCode" style="width: 150px">
          <a-select-option v-for="project in projectList" :value="project.projectCode">{{ project.projectName }}
          </a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item :label-col="{ span: 6 }"
                   :wrapper-col="{ span: 16 }" autocomplete="off"
                   label="模板类型"
                   name="type">
        <a-input v-model:value="queryForm.type" allow-clear/>
      </a-form-item>
      <a-form-item>
        <a-button type="primary" @click="handleQuery">查询</a-button>
        <a-button class="split-button" type="primary" @click="handleReset">重置</a-button>
      </a-form-item>
    </a-form>
  </div>
  <div class="action-buttons-container">
    <a-button class="split-button" type="primary" @click="handleAdd">新增</a-button>
    <a-button class="split-button" type="primary" :disabled="!singleSelect" @click="handleEdit(null)">修改
    </a-button>
    <a-popconfirm
        title="确定删除这条记录?"
        ok-text="确定"
        cancel-text="取消"
        @confirm="handleDelete(null)"
        :disabled="!singleSelect"
    >
      <a-button class="split-button" type="danger" :disabled="!singleSelect">删除</a-button>
    </a-popconfirm>
  </div>
  <a-table :data-source="sysGenTemplateList" :columns="columns" rowKey="id"
           :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
           :pagination="false"
  >
    <template #bodyCell="{ column, record }">
      <template v-if="column.key === 'action'">
        <a-button type="primary" @click="handleOpenTemplateDiag(record)">编辑模板内容</a-button>
      </template>
    </template>
  </a-table>
  <div style="text-align: right;padding-top: 20px;padding-bottom: 20px;">
    <a-pagination @change="handlePageChange" :total="pagination.total" :page-size="pagination.pageSize"
                  :current="pagination.current"/>
  </div>
  <a-modal v-model:visible="showAddModel" title="新增或修改模板" @ok="handleSave">
    <a-form ref="addFormRef" :model="addForm"
            :label-col="{ span: 6 }"
            :wrapper-col="{ span: 16 }" autocomplete="off">
      <a-form-item style="display: none;"
                   label="id"
                   name="id">
        <a-input v-model:value="addForm.id"/>
      </a-form-item>
      <a-form-item
          label="项目"
          name="projectCode"
          :rules="[{ required: true, message: '请选择项目编码' }]"
      >
        <a-select v-model:value="addForm.projectCode" style="width: 150px">
          <a-select-option v-for="project in projectList" :value="project.projectCode">{{ project.projectName }}
          </a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item
          label="模板名字"
          name="templateName"
          :rules="[{ required: true, message: '请输入模板名字' }]"
      >
        <a-input v-model:value="addForm.templateName"/>
      </a-form-item>
      <a-form-item
          label="源文件类型"
          name="sourceType"
          :rules="[{ required: true, message: '请输入源文件类型' }]"
      >
        <a-input v-model:value="addForm.sourceType"/>
      </a-form-item>
      <a-form-item
          label="模板类型"
          name="type"
          :rules="[{ required: false, message: '请输入模板类型' }]"
      >
        <a-input v-model:value="addForm.type"/>
      </a-form-item>
    </a-form>
  </a-modal>
  <a-modal v-model:visible="openTemplateDiag" title="编辑模板内容" style="width:80%;top:50px;" :keyboard="false"
           :maskClosable="false" :bodyStyle="{'height':'calc(100vh - 200px)'}" ok-text="保存" @ok="handleSaveTemplate">
    <div style="height:100%;">
      <div style="height:100%;" v-if="templateDiagData.showCode">
        <div style="flex-grow: 0;padding-bottom: 20px;">
          <a-form layout="inline">
            <a-form-item label="表">
              <a-select v-model:value="templateDiagData.modelId" style="width: 150px">
                <a-select-option v-for="model in modelList" :value="model.id">
                  {{ model.tableComment }}
                </a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item>
              <a-button @click="templateDiagData.showCode=false" type="">返回</a-button>
              <a-button class="split-button" @click="handlePreviewCode" type="primary">渲染</a-button>
            </a-form-item>
          </a-form>
        </div>
        <div
            style="font-family: 'JetBrainsMono-Light';height:calc(100% - 40px);overflow: auto;border:1px #ccc solid;padding:10px;">
          <pre><code v-html="templateDiagData.code"></code></pre>
        </div>
      </div>
      <div v-else style="height:100%;display: flex;flex-direction: column;">
        <div style="flex-grow: 0;padding-bottom: 20px;">
          <a-form layout="inline">
            <a-form-item>
              <a-button type="primary" @click="handleShowRenderedCode">预览代码</a-button>
            </a-form-item>
          </a-form>
        </div>
        <div style="flex-grow: 1;">
          <a-textarea style="height:100%;font-family: 'JetBrainsMono-Light';resize:none;" spellcheck="false"
                      v-model:value="templateDiagData.template" placeholder="在此输入模板内容">
          </a-textarea>
        </div>
      </div>
    </div>
  </a-modal>
</template>
<script setup>

import {onMounted, reactive, ref} from "vue";
import request from '@/util/request.js'
import {message} from "ant-design-vue";
import {showLoading,hideLoading, validValue} from "@/util/util.js";
import hljs from 'highlight.js/lib/core';
import 'highlight.js/styles/github.css';
import java from 'highlight.js/lib/languages/java';
import xml from 'highlight.js/lib/languages/xml';
import html from 'highlight.js/lib/languages/xml';
import vue from 'highlight.js/lib/languages/xml';
import javascript from 'highlight.js/lib/languages/javascript';
import sql from 'highlight.js/lib/languages/sql';

hljs.registerLanguage('java', java);
hljs.registerLanguage('xml', xml);
hljs.registerLanguage('html', html);
hljs.registerLanguage('vue', vue);
hljs.registerLanguage('javascript', javascript);
hljs.registerLanguage('sql', sql);


let showAddModel = ref(false)
let addModelTitle = ref("新增")
let queryForm = reactive({})
let sysGenTemplateList = ref([])
let singleSelect = ref(false)
let selectedRowKeys = ref([])
let selectedRows = ref([])
let addForm = ref({})
let pagination = ref({
  total: 0,
  current: 1,
  pageSize: 10,
})
const queryFormRef = ref(null);
let addFormRef = ref(null);
const columns = [
  {
    title: '模板名字',
    dataIndex: 'templateName',
    key: 'templateName',
  },
  {
    title: '源文件类型',
    dataIndex: 'sourceType',
    key: 'sourceType',
  },
  {
    title: '所属项目',
    dataIndex: 'projectName',
    key: 'projectName',
  },
  {
    title: '模板类型',
    dataIndex: 'type',
    key: 'type',
  },

  {
    title: '创建人',
    dataIndex: 'createdBy',
    key: 'createdBy',
  },
  {
    title: '创建时间',
    dataIndex: 'createdTime',
    key: 'createdTime',
  },
  {
    title: '更新人',
    dataIndex: 'updatedBy',
    key: 'updatedBy',
  },
  {
    title: '更新时间',
    dataIndex: 'updatedTime',
    key: 'updatedTime',
  },
  {
    title: '操作',
    dataIndex: 'action',
    key: 'action',
  },
]
const projectList = ref([]);
let modelList = reactive([]);
onMounted(() => {
  showLoading()
  handleQuery()
  //加载项目列表
  request({
    method: 'post',
    url: '/api/system/gen/project/list',
    data: {}
  }).then((response) => {
    hideLoading()
    const list = response.data;
    projectList.value = list;
  });
  //加载表列表
  showLoading()
  request({
    method: 'post',
    url: '/api/system/gen/model/list',
    data: {}
  }).then((response) => {
    hideLoading()
    const list = response.data;
    modelList = list;
  });
})
const handleQuery = () => {
  let queryParam = {...queryForm};
  queryParam["currentPage"] = pagination.value.current
  queryParam["pageSize"] = pagination.value.pageSize
  query(queryParam)
}

function handleReset() {
  queryFormRef.value.resetFields();
  handleQuery()
}

const query = (param) => {
  showLoading()
  //请求后端
  request({
    method: 'post',
    url: '/api/sysgen/template/page',
    data: param
  }).then((response) => {
    hideLoading()
    let pager = response.data;
    sysGenTemplateList.value = pager.rows;
    pagination.value.current = pager.currentPage
    pagination.value.pageSize = pager.pageSize
    pagination.value.total = pager.totalCount
  });
}
const handlePageChange = (current) => {
  pagination.value.current = current
  handleQuery()
}

function handleSave() {
  addFormRef.value.validate().then((res) => {
    showLoading()
    request({
      method: 'post',
      url: '/api/sysgen/template/addOrUpdate',
      data: res
    }).then((res) => {
      hideLoading()
      if (res.code === 200) {
        showAddModel.value = false;
        message.success("保存成功")
        handleQuery();
      } else {
        message.error("操作失败" + res.errMsg)
      }
    })
  }).catch(() => {
    hideLoading()
  })
}

function handleAdd() {
  //新增
  addModelTitle.value = '新增'
  showAddModel.value = true
  addForm.value = {};
}

function handleEdit(row) {
  showAddModel.value = true
  addModelTitle.value = '修改'
  //加载数据
  if (!validValue(row)) {
    row = selectedRows.value[0];
  }
  addForm.value = {};
  showLoading()
  request({
    method: 'get',
    url: '/api/sysgen/template/selectById',
    params: {id: row.id}
  }).then((res) => {
    hideLoading()
    addForm.value = res.data
  })
}

function handleDelete(row) {
  if (!validValue(row)) {
    row = selectedRows.value[0];
  }
  showLoading()
  request({
    method: 'delete',
    url: '/api/sysgen/template/deleteById',
    params: {id: row.id}
  }).then((res) => {
    hideLoading()
    if (res.code === 200) {
      message.info('删除成功');
      handleQuery()
    } else {
      message.error("删除失败")
    }
  })
}

function onSelectChange(rowKeys, rows) {
  selectedRowKeys.value = rowKeys
  selectedRows.value = rows
  singleSelect.value = rowKeys && rowKeys.length === 1
}

function activated() {
  console.log('activated');
}

//打开模板编辑弹窗
const openTemplateDiag = ref(false);
const templateDiagData = reactive({})

function handleOpenTemplateDiag(row) {
  openTemplateDiag.value = true;
  templateDiagData.showCode = false;
  templateDiagData.template = row.template;
  templateDiagData.id = row.id
  templateDiagData.code = ''
  templateDiagData.sourceType = row.sourceType
}

function handleShowRenderedCode() {
  templateDiagData.showCode = true
}

function handleSaveTemplate() {
  showLoading()
  request({
    method: 'post',
    url: '/api/sysgen/template/addOrUpdate',
    data: {id: templateDiagData.id, template: templateDiagData.template}
  }).then((res) => {
    hideLoading()
    if (res.code === 200) {
      message.info('保存成功');
      handleQuery()
    } else {
      message.error("操作失败")
    }
  })
  openTemplateDiag.value = false
}

function handlePreviewCode() {
  //组合模板和模型，生成代码供预览
  //表id
  //模板内容
  if (!!!templateDiagData.modelId) {
    message.error("请先选择一个表")
    return
  }
  showLoading()
  request({
    method: 'post',
    url: '/api/sysgen/template/previewCode',
    data: {modelId: templateDiagData.modelId, template: templateDiagData.template}
  }).then((res) => {
    hideLoading()
    if (res.code === 200) {
      const result = hljs.highlight( res.data || "", {language:templateDiagData.sourceType});
      templateDiagData.code = result.value
    } else {
      message.error("操作失败")
    }
  });
}
</script>
